package com.sxf.core.script;

import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.FileReader;
import java.sql.Connection;

/**
 * @description: 执行数据库脚本
 * @author:
 * @date:
 */
public class DbExecScriptClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(DbExecScriptClient.class);
    private Connection conn;
    
    public DbExecScriptClient(Connection conn) {
        this.conn = conn;
    }
    
    /**
     * 执行数据库脚本
     * @param scriptPath 脚本地址,例如：classpath:db/init.sql
     * @param stopOnError 出错是否停止
     */
    public void exec(String scriptPath, boolean stopOnError) {
        ScriptRunner sr = new ScriptRunner(conn);
        sr.setStopOnError(stopOnError);
        try {
            sr.runScript(new FileReader(ResourceUtils.getFile(scriptPath)));
        } catch (Exception e) {
            LOGGER.error("执行脚本失败", e);
        }
    }
    
    public void exec(String scriptPath) {
        exec(scriptPath, true);
    }

}
